package linker.account;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;

/**
 * The connection class
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */
public class Connect {

	// The XMPP connection
	private static XMPPConnection connection;

	/**
	 * 
	 * @return xmppconnection The current connection
	 */
	public static XMPPConnection getConnecdtion() {
		return connection;
	}

	/**
	 * The login function of xmppConnection With 5 tries.
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	public static boolean login(String username, String password, String host,
			String portStr, String domain) {
		int port = 5222;

		if (domain == null) {
			domain = username.substring(username.indexOf("@") + 1);
			System.out.println("Domain:" + domain);
		}

		if (portStr != null) {
			port = Integer.parseInt(portStr);
			System.out.println("Port:" + port);
		}

		if (host == null) {
			if (username.endsWith("gmail.com"))
				host = "talk.google.com";
			else if (username.endsWith("xiaonei.com"))
				host = "talk.xiaonei.com";
			else
				host = "talk.jabber.org";
			System.out.println("Host:" + host);
		}

		ConnectionConfiguration config = new ConnectionConfiguration(host,
				port, domain);

		config.setSASLAuthenticationEnabled(true); 
		config.setSecurityMode(SecurityMode.enabled); 

		config.setDebuggerEnabled(true);

		// Create new Xmpp connection with the Gtalk configuration
		connection = new XMPPConnection(config);

		try {
			System.out.println("start to connect");
			connection.connect();
			System.out.println("connected");
			connection.login(username, password);

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	/**
	 * Disconnect from xmpp server
	 * 
	 */
	public static void disConnect() {
		connection.disconnect();
	}
}
